package com.jacky.iot.resources;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.Utils;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
import org.eclipse.californium.core.coap.Request;
import org.eclipse.californium.core.server.resources.CoapExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DefaultTestResource extends CoapResource {

    private static final Logger log = LoggerFactory.getLogger(DefaultTestResource.class);

    public DefaultTestResource(String name) {
        super(name);
        getAttributes().setTitle("Default test resource");
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        StringBuilder payload = new StringBuilder();
        Request request = exchange.advanced().getRequest();
        String hexString = Utils.toHexString(request.getBytes());
        log.info("[GET] req hexString:{}", hexString);
        payload.append(String.format("Type: %d (%s)\nCode: %d (%s)\nMid: %d",
                request.getType().value,
                request.getType(),
                request.getCode().value,
                request.getCode(),
                request.getMID()));

        if (request.getToken() != null) {
            payload.append("\nToken:");
            payload.append(request.getTokenString());
        }

        if (payload.length() > 64) {
            payload.delete(62, payload.length());
            payload.append('»');
        }

        exchange.setMaxAge(30);
        exchange.respond(CoAP.ResponseCode.CONTENT, payload.toString(), MediaTypeRegistry.TEXT_PLAIN);
    }

    @Override
    public void handlePOST(CoapExchange exchange) {
        String hexString = Utils.toHexString(exchange.advanced().getRequest().getBytes());
        log.info("[POST] req hexString:{}", hexString);
        exchange.setLocationPath("location1/location2/location3");
        exchange.respond(CoAP.ResponseCode.CREATED);
    }

    @Override
    public void handlePUT(CoapExchange exchange) {
        String hexString = Utils.toHexString(exchange.advanced().getRequest().getBytes());
        log.info("[PUT] req hexString:{}", hexString);
        if (exchange.getRequestOptions().hasIfNoneMatch()) {
            exchange.respond(CoAP.ResponseCode.PRECONDITION_FAILED);
        } else {
            exchange.respond(CoAP.ResponseCode.CHANGED);
        }
    }

    @Override
    public void handleDELETE(CoapExchange exchange) {
        String hexString = Utils.toHexString(exchange.advanced().getRequest().getBytes());
        log.info("[DELETE] req hexString:{}", hexString);
        exchange.respond(CoAP.ResponseCode.DELETED);
    }
}
